package com.abe.libquick.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkRequest;

import com.abe.libcore.AbeApplication;
import com.abe.libcore.utils.ForegroundCallbacks;
import com.abe.libcore.utils.context.ContextUtils;
import com.abe.libcore.utils.net.NetworkCallbackImpl;

@SuppressLint("NewApi")
public class BaseApplication extends AbeApplication implements ForegroundCallbacks.Listener {

    private static boolean isForeground = true;
    private NetworkCallbackImpl networkCallback;

    public static boolean isForeground() {
        return isForeground;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        ApplicationHelper.init(this);
        ContextUtils.Companion.init(this);
        //监听APP前台后台状态
        ForegroundCallbacks foregroundCallbacks = ForegroundCallbacks.init(this);
        foregroundCallbacks.addListener(this);
        initNetWorkCallback();
    }

    @Override
    public void onBecameForeground() {
        isForeground = true;
    }

    @Override
    public void onBecameBackground() {
        isForeground = false;
    }

    private void initNetWorkCallback() {
        networkCallback = new NetworkCallbackImpl();
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        NetworkRequest request = builder.build();
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connMgr != null) {
            connMgr.registerNetworkCallback(request, networkCallback);
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connMgr != null && networkCallback != null) {
            connMgr.unregisterNetworkCallback(networkCallback);
        }
    }
}